/*
    SlideScript - minimalistic top-down scripting language.
    (C) Copyright 2014-2022 Chris Dorman - some rights reserved (GPLv2)

    View README file supplied with this software for more details
*/

#include "inc/deps.h"
#include "inc/search.h"
#include "inc/util.h"

regex_t pattern;

static char retbuf[MAX_SEARCH_BUFSIZE];

char *ss_search(const char *filename, FILE *fp, char *pat)
{
    char *s_buf = NULL;
    size_t size = 0;
    int ret;
    int flags = REG_NOSUB;  /* don't need where-matched info */

    bzero(retbuf, MAX_SEARCH_LEN);

    regcomp(&pattern, pat, flags);

    while(getline(&s_buf, &size, fp) != -1) 
    {
        ret = regexec(&pattern, s_buf, 0, NULL, 0);
        if (ret != 0) 
        {
            if (ret != REG_NOMATCH) {
                syn_warn("ss:warn:search, pattern not found");
                free(s_buf);
                return NULL;
            }
        } 
        else 
        {
            if(strlen(s_buf) < MAX_SEARCH_LEN)
            {
                char tmpbuf[strlen(s_buf) + strlen(filename) + 7];
                sprintf(tmpbuf, "ss: %s: %s", filename, s_buf);
                strcat(retbuf, tmpbuf);
                bzero(tmpbuf, strlen(tmpbuf));
            }
            else
            {
                syn_warn("ss:warn:search, static buffer maxed");
            }
        }
    }

    free(s_buf);

    regfree(&pattern);

    return retbuf;
}
